import { OneModal } from '@/components/one-ui';
import { ContractManageAPI } from '../common/type';
import { UpdateTableCommon } from './UpdateTableCommon';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useRef, useState } from 'react';
import { openContractSubjectManage } from '../services';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { contractMainTableColumns } from '../mconfig';
import { message } from 'antd';
import { onCloseModalCommon } from '@/utils';

export const OpenContractMainBodyModal: React.FC<ContractManageAPI.IOpenContractMainBodyModal> = ({ onClose, contractFormName, oppositeCode }) => {
  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);

  /** 获取上下文 */
  const { curRes, styleFixCls, contractDetailInfo, contractDispatch } = useContext(ConractControllerContext);

  /** 保存选中数据 */
  const [selectSubjectInfo, setSelectSubjectInfo] = useState<Record<string, any>>({});

  /** 获取列表 */
  const { data, params, loading, pagination, searchList, getManageData } = openContractSubjectManage(curRes, true);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo: any) => {
    setSelectSubjectInfo(selectInfo);
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 初始化 */
  useEffect(() => {
    if (data?.rows?.length > 0) {
      const oppositeInfo: Record<string, any> = contractFormName?.getFieldsValue();
      const selectRows: Record<string, any> = data?.rows?.find((item: any) => item?.id == oppositeInfo?.oppositeID);
      setSelectSubjectInfo(selectRows);
    }
  }, [data?.rows]);

  /** 保存方法 */
  const saveSubject = () => {
    if (selectSubjectInfo && JSON.stringify(selectSubjectInfo) != '{}') {
      if (oppositeCode?.includes(selectSubjectInfo?.creditID)) {
        message.warning('请换一位合同主体！');
      } else {
        const partyInfo: Record<string, any> = {
          oppositeName: selectSubjectInfo?.oppositeName,
          oppositeID: selectSubjectInfo?.id,
          // phoneMobile: selectSubjectInfo?.contactMobile,
          contactName: selectSubjectInfo?.contactName,
          creditID: selectSubjectInfo?.creditID,
          bankName: selectSubjectInfo?.bankName,
          bankAccount: selectSubjectInfo?.bankAccount,
          registerPhone: selectSubjectInfo?.registerPhone,
          workAddress: selectSubjectInfo?.workAddress,
          partyId: selectSubjectInfo?.id,
        };

        contractDispatch({
          type: IContractsActionEnum.SELECT_PARTYALIST,
          payload: [partyInfo],
        });

        contractFormName?.setFieldsValue(partyInfo);

        onCloseModalCommon(updateModalRef);
      }
    } else {
      message.warning('请选择一位合同主体！');
    }
  };

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={updateModalRef}
      title={'合同主体'}
      onCancel={onClose}
      width={document.body.clientWidth * 0.65}
      bodyStyle={{
        height: document.body.clientHeight * 0.55,
        padding: 0,
      }}
      onOk={saveSubject}
    >
      <UpdateTableCommon
        styleFixCls={styleFixCls}
        searchProps={{
          searchList,
          onReset,
          onSearch,
        }}
        selectTablePorps={{
          onSelectTable,
          selectRowObjList: selectSubjectInfo && JSON.stringify(selectSubjectInfo) != '{}' ? [selectSubjectInfo] : [],
          getCheckboxProps: (record) => {
            if (oppositeCode) {
              return {
                disabled: oppositeCode?.includes(record?.creditID),
              };
            }
          },
          notCreditIDList: oppositeCode ? oppositeCode : [],
        }}
        tableProps={{
          columns: contractMainTableColumns(),
          loading,
          dataSource: data?.rows,
          pagination,
          onPageChange,
        }}
      />
    </OneModal>
  );
};
